package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * 登录控制器
 */
@RestController
@RequestMapping("/mobile/login")
@Slf4j
public class MobileLoginController {
    @Autowired
    private MemberService memberService;
    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping("/smsLogin")
    public Result smsLogin(@RequestBody Map map) {
        //从map中获取前端传来的手机号和验证码
        String phoneNumber = (String) map.get("telephone");
        String code = (String) map.get("validateCode");
        System.out.println("手机号是" + phoneNumber + "验证码" + code);
        //如果是空验证码就报错
        if (code == null) {
            throw new BusinessRuntimeException("验证码不能为空");
        }
        //根据手机号从redis中取出redis的验证码
        Object redisCode = redisTemplate.opsForValue().get("MOBILE_SIGNIN_" + phoneNumber);
        //比对之前存的验证码和接收到的验证码
        if (!code.equals(redisCode)) {
            throw new BusinessRuntimeException("请输入正确的验证码");

        } else {
            redisTemplate.delete(phoneNumber);
        }
        Member member = memberService.getMemberByPhone(phoneNumber);
        if (member == null) {
            Member member1 = new Member();
            member1.setPhoneNumber(phoneNumber);
            memberService.save(member1);
        }
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }
}
